package com.seven.ezpermissions.sample

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.seven.ezpermissions.AppSettingsDialog
import com.seven.ezpermissions.EzPermissions
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    companion object {
        private const val PERMISSIONS_REQUEST_CODE_PHONE_CALL = 1001
        private const val PERMISSIONS_REQUEST_CODE_CAMERA = 1002
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnRequestPhoneCall.setOnClickListener {
            requestPhoneCallPermissions()
        }

        btnRequestCamera.setOnClickListener {
            requestCameraPermissions()
        }

        btnNext.setOnClickListener {
            startActivity(Intent(this, FragmentSampleActivity::class.java))
        }

        btnFinishNext.setOnClickListener {
            startActivity(Intent(this, FragmentSampleActivity::class.java))
            finish()
        }
    }

    private fun requestPhoneCallPermissions() {
        EzPermissions.request(
            this,
            arrayOf(Manifest.permission.CALL_PHONE),
            PERMISSIONS_REQUEST_CODE_PHONE_CALL,
            onGranted = { requestCode ->
                toast("Permissions Granted: requestCode=$requestCode")
            },
            onDenied = { requestCode, denied ->
                toast("Permissions Denied: requestCode=$requestCode,permissions=$denied")
                AppSettingsDialog.Builder(this).build().show()
            })
    }

    private fun requestCameraPermissions() {
        EzPermissions.request(
            this,
            arrayOf(Manifest.permission.CAMERA),
            PERMISSIONS_REQUEST_CODE_CAMERA,
            onGranted = { requestCode ->
                toast("Permissions Granted: requestCode=$requestCode")
            },
            onDenied = { requestCode, denied ->
                toast("Permissions Denied: requestCode=$requestCode,permissions=$denied")
                AppSettingsDialog.Builder(this).build().show()
            })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EzPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun toast(text: String) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
    }
}